﻿#include "FrameBufferStack.h"

void FrameBufferStack::Push(const Ref<FrameBuffer> &fb)
{
  LOG_TRACE("Push framebuffer");
  m_stack.push_back(fb);
  fb->Bind();

  if (m_keepIntermediateTextures)
  {
    for (int i = 0; i < fb->GetColorAttachmentCount(); i++)
    {
      m_intermediateTextures.push_back(fb->GetColorAttachment(i));
    }
  }
}

Ref<FrameBuffer> FrameBufferStack::Pop()
{
  assert(!IsEmpty());
  LOG_TRACE("Pop framebuffer");

  Ref<FrameBuffer> fb = Peek();
  m_stack.pop_back();

  auto current = Peek();
  if (current != nullptr)
    current->Bind();
  else
    fb->Unbind();

  return fb;
}

Ref<FrameBuffer> FrameBufferStack::Peek()
{
  return IsEmpty() ? nullptr : m_stack.back();
}

void FrameBufferStack::SetKeepIntermediateTextures(bool keep)
{
  m_keepIntermediateTextures = keep;
}

void FrameBufferStack::ClearIntermediateTexturesReferences()
{
  m_intermediateTextures.clear();
}

std::vector<Ref<Texture>> FrameBufferStack::GetIntermediateTextures()
{
  return m_intermediateTextures;
}

bool FrameBufferStack::IsEmpty() const
{
  return m_stack.empty();
}

size_t FrameBufferStack::GetSize() const
{
  return m_stack.size();
}